﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class Program
	{
		public Namespace[] Namespaces { get; private set; }

		public Program(ICollection<Namespace> namespaces)
		{
			this.Namespaces = namespaces.ToArray<Namespace>();
		}

		public void AddBuiltIns(IList<Namespace> builtins)
		{
			List<Namespace> namespaces = new List<Namespace>(this.Namespaces);
			namespaces.AddRange(builtins);
			this.Namespaces = namespaces.ToArray();
		}

		public void Merge(Program program)
		{
			Dictionary<string, Namespace> a = this.GetNamespaceLookup();
			Dictionary<string, Namespace> b = program.GetNamespaceLookup();
			foreach (string key in b.Keys)
			{
				if (a.ContainsKey(key))
				{
					a[key].Merge(b[key]);
				}
				else
				{
					a[key] = b[key];
				}
			}

			this.Namespaces = a.Values.ToArray();
		}

		private Dictionary<string, Namespace> GetNamespaceLookup()
		{
			Dictionary<string, Namespace> namespaces = new Dictionary<string, Namespace>();
			foreach (Namespace ns in this.Namespaces)
			{
				namespaces[ns.Name] = ns;
			}

			return namespaces;
		}
	}
}
